/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.swe.chums.beans;

import com.swe.chums.dao.SourceDao;
import com.swe.chums.dao.UserDao;
import com.swe.chums.dao.WebResourceDao;
import com.swe.chums.dao.exceptions.SourceDaoException;
import com.swe.chums.dao.exceptions.UserDaoException;
import com.swe.chums.dao.exceptions.WebResourceDaoException;
import com.swe.chums.dao.factory.DaoFactory;
import com.swe.chums.dao.model.Source;
import com.swe.chums.dao.model.SourcePk;
import com.swe.chums.dao.model.User;
import com.swe.chums.dao.model.UserPk;
import com.swe.chums.dao.model.WebResource;
import com.swe.chums.dao.model.WebResourcePk;
import com.swe.chums.utils.CommonUtils;
import com.swe.chums.utils.WebResourceTypeEnum;
import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.event.RowEditEvent;
import org.primefaces.event.data.FilterEvent;

/**
 *
 * @author cilingir
 */
@ManagedBean(name = "adminBean")
@ViewScoped
public class AdminBean implements Serializable{

    private static Logger log = Logger.getLogger(AdminBean.class);
    private User toBeRemovedUser, toAddUser;
    private WebResource toBeRemovedWebResource, toAddWebResource;
    private Source toBeRemovedSource, toAddSource;
    private ArrayList<User> lastUsers, allUsers;
    private ArrayList<WebResource> allCourses, allInstructors, allInstitutions;
    private ArrayList<Source> allSources;
    private String password2;
    
    public AdminBean() {
        lastUsers = retrieveLastUsers();
        allUsers = retrieveAllUsers();
        allCourses = retrieveAllCourses();
        allInstructors = retrieveAllInstructors();
        allInstitutions = retrieveAllInstitutions();
        allSources = retrieveAllSources();
    }
    
    /**
     * Get Last Users
     * 
     * @return 
     */
    public ArrayList<User> retrieveLastUsers() {
        
        log.debug("[AdminBean.getLastUsers] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String errorText = "ERROR";
        ArrayList<User> lastUsers = new ArrayList<User>();
        try {
            lastUsers = (ArrayList<User>) DaoFactory.createUserDao().findLatest(5);
        } catch (UserDaoException ex) {
            log.error("[AdminBean.getLastUsers] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        }
        return lastUsers;
    }

    /**
     * Get All Users
     * 
     * @return 
     */
    public ArrayList<User> retrieveAllUsers() {
        log.debug("[AdminBean.getAllUsers] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String errorText = "ERROR";
        ArrayList<User> allUsers = new ArrayList<User>();
        try {
            allUsers = (ArrayList<User>) DaoFactory.createUserDao().findAll();
        } catch (UserDaoException ex) {
            log.error("[AdminBean.getAllUsers] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        }
        return allUsers;
    }
    
    
    /**
     * Get All Courses
     * 
     * @return 
     */
    public ArrayList<WebResource> retrieveAllCourses() {
        log.debug("[AdminBean.retrieveAllCourses] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String errorText = "ERROR";
        allCourses = new ArrayList<WebResource>();
        try {
            allCourses = (ArrayList<WebResource>) DaoFactory.createWebResourceDao().findByWebResourceType(WebResourceTypeEnum.COURSE.getId());
        } catch (WebResourceDaoException ex) {
            log.error("[AdminBean.retrieveAllCourses] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        }
        return allCourses;
    }
    
    
    /**
     * Get All Instructors
     * 
     * @return 
     */
    public ArrayList<WebResource> retrieveAllInstructors() {
        log.debug("[AdminBean.retrieveAllInstructors] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String errorText = "ERROR";
        allInstructors = new ArrayList<WebResource>();
        try {
            allInstructors = (ArrayList<WebResource>) DaoFactory.createWebResourceDao().findByWebResourceType(WebResourceTypeEnum.INSTRUCTOR.getId());
        } catch (WebResourceDaoException ex) {
            log.error("[AdminBean.retrieveAllInstructors] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        }
        return allInstructors;
    }
    
    
    /**
     * Get All Institutions
     * 
     * @return 
     */
    public ArrayList<WebResource> retrieveAllInstitutions() {
        log.debug("[AdminBean.retrieveAllInstitutions] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String errorText = "ERROR";
        allInstitutions = new ArrayList<WebResource>();
        try {
            allInstitutions = (ArrayList<WebResource>) DaoFactory.createWebResourceDao().findByWebResourceType(WebResourceTypeEnum.INSTITUTION.getId());
        } catch (WebResourceDaoException ex) {
            log.error("[AdminBean.retrieveAllInstitutions] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        }
        return allInstitutions;
    }
    
    
    /**
     * Get All Sources
     * 
     * @return 
     */
    public ArrayList<Source> retrieveAllSources() {
        log.debug("[AdminBean.retrieveAllSources] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String errorText = "ERROR";
        allSources = new ArrayList<Source>();
        try {
            allSources = (ArrayList<Source>) DaoFactory.createSourceDao().findAll();
        } catch (SourceDaoException ex) {
            log.error("[AdminBean.retrieveAllSources] - error while retrieving values from DB, message is:  " + ex.getMessage());
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
        }
        return allSources;
    }
    
    
    /**
     * Filter event handler
     *
     * @param event
     * @return
     */
    public Map<String, String> onFilterAllUsers(FilterEvent event) {

        log.debug("[AdminBean.onFilterAllUsers] started");
        Map<String, String> filters;
        DataTable table = (DataTable) event.getSource();

//        List<User> obj = table.getFilteredData();
//        if (obj != null) {
//            table.getFilteredData().remove(obj);
//        }
        filters = table.getFilters();
        filters.clear();

        return filters;
    }
    
    public void removeUserFromAllUsers() {
        log.debug("[AdminBean.removeUserFromAllUsers] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        
        if (toBeRemovedUser != null) {
            User loggedInUser = ((LoginBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("loginBean")).getUser();
            if (loggedInUser.getId() == toBeRemovedUser.getId()) {
                log.error("[AdminBean.removeUserFromAllUsers] - can not remove your own user");
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "Can not delete your own user"));
            } else {
                UserDao dao = DaoFactory.createUserDao();
                UserPk userPk = new UserPk();
                int id = toBeRemovedUser.getId();
                userPk.setId(id);
                try {
                    // remove attached user actions
                    dao.delete(userPk);

                    allUsers.remove(toBeRemovedUser);
                    
                    context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "User removed"));
                    
                } catch (UserDaoException ex) {
                    log.error("[AdminBean.removeUserFromAllUsers] - error while deleting values from DB, message is:  " + ex.getMessage());
                    context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
                }
            }

        } else {
            // You shouldnt be here!
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "No user selected"));
        }
    }
    
    
    
    /**
     * Row edit event for user datatable
     *
     */
    public void onEditAllUsersRow(RowEditEvent event) {
        log.debug("[AdminBean.onEditAllUsersRow] started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        try {
            UserDao userDao = DaoFactory.createUserDao();
            User user = (User) event.getObject();
            UserPk userPk = new UserPk(user.getId());
            User oldUser = userDao.findByPrimaryKey(userPk);

            log.debug("[AdminBean.onEditAllUsersRow], userID to be editted: " + user.getId());

            // validation ifs
            String email = user.getEmail().trim();
            String name = user.getName().trim();
            String username = user.getUsername().trim();
            
            if (name.equals("")) {
                log.error("[AdminBean.onEditAllUsersRow] - name is empty");
                text = "Name is empty";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAlphaNumerical(name)) {
                log.error("[AdminBean.onEditAllUsersRow] - user's name is not in allowed format: " + name);
                text = "Name must be alphanumerical";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(name, 60)) {
                log.error("[AdminBean.onEditAllUsersRow] - user's name is not in allowed length: " + name);
                text = "Name can't be longer than 60 characters";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (username.equals("")) {
                log.error("[AdminBean.onEditAllUsersRow] - username is empty");
                text = "Username is empty";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAlphaNumerical(username)) {
                log.error("[AdminBean.onEditAllUsersRow] - user's username is not in allowed format: " + username);
                text = "Username must be alphanumerical";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(username, 40)) {
                log.error("[AdminBean.onEditAllUsersRow] - user's username is not in allowed length: " + username);
                text = "Username can't be longer than 40 characters";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else {
                if (!username.equals(oldUser.getUsername())) {
                    try {
                        log.debug("[AdminBean.onEditAllUsersRow] - user dao created");
                        ArrayList<User> usernameList = (ArrayList<User>) DaoFactory.createUserDao().findWhereUsernameEquals(username);

                        if (usernameList != null && usernameList.size() > 0) {
                            log.error("[AdminBean.onEditAllUsersRow] - username exists: " + username);
                            text = "Username exists";
                            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
                        }
                    } catch (UserDaoException ex) {
                        log.error("[AdminBean.onEditAllUsersRow] - error while retrieving values from DB, message is:  " + ex.getMessage());
                        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "DB error"));
                    }
                }
            }
            
            if (email.equals("")) {
                log.error("[AdminBean.onEditAllUsersRow] - email is empty");
                text = "Email is empty";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!email.matches("[\\w\\.-]*[a-zA-Z0-9_]@[\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]")) {
                log.error("[AdminBean.onEditAllUsersRow] - email is not in right format: " + email);
                text = "Email is not in correct format";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(email, 70)) {
                log.error("[AdminBean.onEditAllUsersRow] - email is not in allowed length: " + email);
                text = "Email can't be  longer than 70";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else {
                if (!email.equals(oldUser.getEmail())) {
                    try {
                        log.info("[AdminBean.onEditAllUsersRow] - user dao created");
                        ArrayList<User> emailList = (ArrayList<User>) DaoFactory.createUserDao().findWhereEmailEquals(email);

                        if (emailList != null && emailList.size() > 0) {
                            log.error("[AdminBean.onEditAllUsersRow] - email exists: " + email);
                            text = "Email exists";
                            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
                        }
                    } catch (UserDaoException ex) {
                        log.error("[AdminBean.onEditAllUsersRow] - error while retrieving values from DB, message is:  " + ex.getMessage());
                        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "DB error"));
                    }
                }
            }
            
            if (context.getMessageList().size() > 0) {
                // Rollback on error
                user.setName(oldUser.getName());
                user.setEmail(oldUser.getEmail());
                user.setUsername(oldUser.getUsername());

                log.error("[AdminBean.onEditAllUsersRow] - there are errors with the form");
                text = "There are errors with the form";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, text));
            } else {
                // Update user
                DaoFactory.createUserDao().update(userPk, user);
                log.debug("[AdminBean.onEditAllUsersRow] - no errors with the form, user dao created and updated with the id: " + user.getId());

                log.debug("[AdminBean.onEditAllUsersRow] - refreshing user chart");

                String updateText = "Updated successfully";
                String infoText = "INFO";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, infoText, updateText));

            }
        } catch (UserDaoException ex) {
            log.error("[AdminBean.onEditAllUsersRow] - exception message: " + ex.getMessage());
            text = "General error with DB";
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, text));
        }
    }
    
    
    
    /**
     * Filter event handler
     *
     * @param event
     * @return
     */
    public Map<String, String> onFilterAllWebResources(FilterEvent event) {

        log.debug("[AdminBean.onFilterAllWebResources] started");
        Map<String, String> filters;
        DataTable table = (DataTable) event.getSource();

//        List<User> obj = table.getFilteredData();
//        if (obj != null) {
//            table.getFilteredData().remove(obj);
//        }
        filters = table.getFilters();
        filters.clear();

        return filters;
    }
    
    
    /**
     * Filter event handler
     *
     * @param event
     * @return
     */
    public Map<String, String> onFilterAllSources(FilterEvent event) {

        log.debug("[AdminBean.onFilterAllSources] started");
        Map<String, String> filters;
        DataTable table = (DataTable) event.getSource();

//        List<User> obj = table.getFilteredData();
//        if (obj != null) {
//            table.getFilteredData().remove(obj);
//        }
        filters = table.getFilters();
        filters.clear();

        return filters;
    }
    
    
    /**
     * Remove web resource
     * 
     */
    public void removeWebResource() {
        log.debug("[AdminBean.removeWebResource] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        
        if (toBeRemovedWebResource != null) {
            
            WebResourceDao dao = DaoFactory.createWebResourceDao();
            WebResourcePk webResourcePk = new WebResourcePk();
            int id = toBeRemovedWebResource.getId();
            webResourcePk.setId(id);
            try {
                
                dao.delete(webResourcePk);
                
                if (toBeRemovedWebResource.getWebResourceTypeId() == WebResourceTypeEnum.COURSE.getId()) {
                    allCourses.remove(toBeRemovedWebResource);
                } else if (toBeRemovedWebResource.getWebResourceTypeId() == WebResourceTypeEnum.INSTRUCTOR.getId()) {
                    allInstructors.remove(toBeRemovedWebResource);
                } else {
                    allInstitutions.remove(toBeRemovedWebResource);
                }
                
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Succesfully removed"));

            } catch (WebResourceDaoException ex) {
                log.error("[AdminBean.removeWebResource] - error while deleting values from DB, message is:  " + ex.getMessage());
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
            }
            

        } else {
            // You shouldnt be here!
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "Not selected"));
        }
    }
    
    
    /**
     * Remove source
     * 
     */
    public void removeSource() {
        log.debug("[AdminBean.removeSource] - started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        
        if (toBeRemovedSource != null) {
            
            SourceDao dao = DaoFactory.createSourceDao();
            SourcePk sourcePk = new SourcePk();
            int id = toBeRemovedSource.getId();
            sourcePk.setId(id);
            try {
                
                dao.delete(sourcePk);
                
                allSources.remove(toBeRemovedSource);
                
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Succesfully removed"));

            } catch (SourceDaoException ex) {
                log.error("[AdminBean.removeSource] - error while deleting values from DB, message is:  " + ex.getMessage());
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "General DB Error"));
            }
            
        } else {
            // You shouldnt be here!
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, "No source selected"));
        }
    }
    
    
    /**
     * Row edit event for user datatable
     *
     */
    public void onEditAllCoursesRow(RowEditEvent event) {
        log.debug("[AdminBean.onEditAllCoursesRow] started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        try {
            WebResourceDao webResourceDao = DaoFactory.createWebResourceDao();
            WebResource webResource = (WebResource) event.getObject();
            WebResourcePk webResourcePk = new WebResourcePk(webResource.getId());
            WebResource oldWebResource = webResourceDao.findByPrimaryKey(webResourcePk);

            log.debug("[AdminBean.onEditAllCoursesRow], web resource ID to be editted: " + webResource.getId());

            // validation ifs
            String title = webResource.getTitle().trim();
            String description = webResource.getDescription().trim();
            
            
            if (title.equals("")) {
                log.error("[AdminBean.onEditAllCoursesRow] - name is empty");
                text = "Title is empty";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(title, 240)) {
                log.error("[AdminBean.onEditAllCoursesRow] - user's name is not in allowed length: " + title);
                text = "Title can't be longer than 240 characters";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (description.equals("")) {
                log.error("[AdminBean.onEditAllCoursesRow] - name is empty");
                text = "Description is empty";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (context.getMessageList().size() > 0) {
                // Rollback on error
                webResource.setTitle(oldWebResource.getTitle());
                webResource.setDescription(oldWebResource.getDescription());
                
                log.error("[AdminBean.onEditAllCoursesRow] - there are errors with the form");
                text = "There are errors with the form";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, text));
            } else {
                // Update user
                webResourceDao.update(webResourcePk, webResource);
                log.debug("[AdminBean.onEditAllUsersRow] - no errors with the form, webResource dao created and updated with the id: " + webResource.getId());

                String updateText = "Updated successfully";
                String infoText = "INFO";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, infoText, updateText));

            }
        } catch (WebResourceDaoException ex) {
            log.error("[AdminBean.onEditAllCoursesRow] - exception message: " + ex.getMessage());
            text = "General error with DB";
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, text));
        }
    }
            
    
    /**
     * Row edit event for user datatable
     *
     */
    public void onEditAllInstructorsRow(RowEditEvent event) {
        log.debug("[AdminBean.onEditAllInstructorsRow] started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        try {
            WebResourceDao webResourceDao = DaoFactory.createWebResourceDao();
            WebResource webResource = (WebResource) event.getObject();
            WebResourcePk webResourcePk = new WebResourcePk(webResource.getId());
            WebResource oldWebResource = webResourceDao.findByPrimaryKey(webResourcePk);

            log.debug("[AdminBean.onEditAllInstructorsRow], web resource ID to be editted: " + webResource.getId());

            // validation ifs
            String title = webResource.getTitle().trim();
            String description = webResource.getDescription().trim();
            
            
            if (title.equals("")) {
                log.error("[AdminBean.onEditAllInstructorsRow] - name is empty");
                text = "Name is empty";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(title, 240)) {
                log.error("[AdminBean.onEditAllInstructorsRow] - user's name is not in allowed length: " + title);
                text = "Name can't be longer than 240 characters";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (description.equals("")) {
                log.error("[AdminBean.onEditAllInstructorsRow] - name is empty");
                text = "Description is empty";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (context.getMessageList().size() > 0) {
                // Rollback on error
                webResource.setTitle(oldWebResource.getTitle());
                webResource.setDescription(oldWebResource.getDescription());
                
                log.error("[AdminBean.onEditAllInstructorsRow] - there are errors with the form");
                text = "There are errors with the form";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, text));
            } else {
                // Update user
                webResourceDao.update(webResourcePk, webResource);
                log.debug("[AdminBean.onEditAllInstructorsRow] - no errors with the form, webResource dao created and updated with the id: " + webResource.getId());

                String updateText = "Updated successfully";
                String infoText = "INFO";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, infoText, updateText));

            }
        } catch (WebResourceDaoException ex) {
            log.error("[AdminBean.onEditAllInstructorsRow] - exception message: " + ex.getMessage());
            text = "General error with DB";
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, text));
        }
    }
    
    
    /**
     * Row edit event for user datatable
     *
     */
    public void onEditAllInstitutionsRow(RowEditEvent event) {
        log.debug("[AdminBean.onEditAllInstitutionsRow] started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        try {
            WebResourceDao webResourceDao = DaoFactory.createWebResourceDao();
            WebResource webResource = (WebResource) event.getObject();
            WebResourcePk webResourcePk = new WebResourcePk(webResource.getId());
            WebResource oldWebResource = webResourceDao.findByPrimaryKey(webResourcePk);

            log.debug("[AdminBean.onEditAllInstitutionsRow], web resource ID to be editted: " + webResource.getId());

            // validation ifs
            String title = webResource.getTitle().trim();
            String description = webResource.getDescription().trim();
            
            
            if (title.equals("")) {
                log.error("[AdminBean.onEditAllInstitutionsRow] - name is empty");
                text = "Title is empty";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(title, 240)) {
                log.error("[AdminBean.onEditAllInstitutionsRow] - user's name is not in allowed length: " + title);
                text = "Title can't be longer than 240 characters";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (description.equals("")) {
                log.error("[AdminBean.onEditAllInstitutionsRow] - name is empty");
                text = "Description is empty";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (context.getMessageList().size() > 0) {
                // Rollback on error
                webResource.setTitle(oldWebResource.getTitle());
                webResource.setDescription(oldWebResource.getDescription());
                
                log.error("[AdminBean.onEditAllInstitutionsRow] - there are errors with the form");
                text = "There are errors with the form";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, text));
            } else {
                // Update user
                webResourceDao.update(webResourcePk, webResource);
                log.debug("[AdminBean.onEditAllInstitutionsRow] - no errors with the form, webResource dao created and updated with the id: " + webResource.getId());

                String updateText = "Updated successfully";
                String infoText = "INFO";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, infoText, updateText));

            }
        } catch (WebResourceDaoException ex) {
            log.error("[AdminBean.onEditAllInstitutionsRow] - exception message: " + ex.getMessage());
            text = "General error with DB";
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, text));
        }
    }

    
    /**
     * Row edit event for user datatable
     *
     */
    public void onEditAllSourcesRow(RowEditEvent event) {
        log.debug("[AdminBean.onEditAllCoursesRow] started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        try {
            SourceDao sourceDao = DaoFactory.createSourceDao();
            Source source = (Source) event.getObject();
            SourcePk sourcePk = new SourcePk(source.getId());
            Source oldSource = sourceDao.findByPrimaryKey(sourcePk);

            log.debug("[AdminBean.onEditAllUsersRow], source ID to be editted: " + source.getId());

            // validation ifs
            String name = source.getName().trim();
            
            if (name.equals("")) {
                log.error("[AdminBean.onEditAllUsersRow] - name is empty");
                text = "Address is empty";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(name, 80)) {
                log.error("[AdminBean.onEditAllUsersRow] - user's name is not in allowed length: " + name);
                text = "Address can't be longer than 60 characters";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else {
                if (!name.equals(oldSource.getName())) {
                    try {
                        log.debug("[AdminBean.onEditAllUsersRow] - source dao created");
                        ArrayList<Source> sourceList = (ArrayList<Source>) DaoFactory.createSourceDao().findWhereNameEquals(name);

                        if (sourceList != null && sourceList.size() > 0) {
                            log.error("[AdminBean.onEditAllUsersRow] - address exists: " + name);
                            text = "Address exists";
                            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
                        }
                    } catch (SourceDaoException ex) {
                        log.error("[AdminBean.onEditAllUsersRow] - error while retrieving values from DB, message is:  " + ex.getMessage());
                        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "DB error"));
                    }
                }
            }
            
            if (context.getMessageList().size() > 0) {
                // Rollback on error
                source.setName(oldSource.getName());
                
                log.error("[AdminBean.onEditAllUsersRow] - there are errors with the form");
                text = "There are errors with the form";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, text));
            } else {
                // Update user
                DaoFactory.createSourceDao().update(sourcePk, source);
                log.debug("[AdminBean.onEditAllUsersRow] - no errors with the form, source dao created and updated with the id: " + source.getId());

                log.debug("[AdminBean.onEditAllUsersRow] - refreshing user chart");

                String updateText = "Updated successfully";
                String infoText = "INFO";
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, infoText, updateText));

            }
        } catch (SourceDaoException ex) {
            log.error("[AdminBean.onEditAllCoursesRow] - exception message: " + ex.getMessage());
            text = "General error with DB";
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, errorText, text));
        }
    }
    
    /**
     * Add user
     * 
     * @return 
     */
    public String addUser() {
        log.debug("[AdminBean.addUser] started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        
        try {
            
            if (toAddUser.getName() != null && !toAddUser.getName().equals("")) {
                toAddUser.setName(toAddUser.getName().trim());
            } else {
                toAddUser.setName("");
            }
            
            if (toAddUser.getUsername() != null && !toAddUser.getUsername().equals("")) {
                toAddUser.setUsername(toAddUser.getUsername().trim());
            } else {
                toAddUser.setUsername("");
            }
            
            if (toAddUser.getPassword() != null && !toAddUser.getPassword().equals("")) {
                toAddUser.setPassword(toAddUser.getPassword().trim());
            } else {
                toAddUser.setPassword("");
            }
            
            if (password2 != null && !password2.equals("")) {
                password2 = password2.trim();
            } else {
                password2 = "";
            }
            
            if (toAddUser.getEmail() != null && !toAddUser.getEmail().equals("")) {
                toAddUser.setEmail(toAddUser.getEmail().trim());
            } else {
                toAddUser.setEmail("");
            }
            
            
            if (toAddUser.getName().equals("")) {
                log.error("[AdminBean.register] - name is empty");
                text = "Name is empty";
                context.addMessage("form:name", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAlphaNumerical(toAddUser.getName())) {
                log.error("[AdminBean.register] - user's name is not in allowed format: " + toAddUser.getName());
                text = "Name must be alphanumerical";
                context.addMessage("form:name", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(toAddUser.getName(), 60)) {
                log.error("[AdminBean.register] - user's name is not in allowed length: " + toAddUser.getName());
                text = "Name can't be longer than 60 characters";
                context.addMessage("form:name", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (toAddUser.getUsername().equals("")) {
                log.error("[AdminBean.register] - username is empty");
                text = "Username is empty";
                context.addMessage("form:username", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAlphaNumerical(toAddUser.getUsername())) {
                log.error("[AdminBean.register] - user's username is not in allowed format: " + toAddUser.getUsername());
                text = "Username must be alphanumerical";
                context.addMessage("form:username", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(toAddUser.getUsername(), 40)) {
                log.error("[AdminBean.register] - user's username is not in allowed length: " + toAddUser.getUsername());
                text = "Username can't be longer than 40 characters";
                context.addMessage("form:username", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else {
                try {
                    log.debug("[AdminBean.register] - user dao created");
                    ArrayList<User> usernameList = (ArrayList<User>) DaoFactory.createUserDao().findWhereUsernameEquals(toAddUser.getUsername());

                    if (usernameList != null && usernameList.size() > 0) {
                        log.error("[AdminBean.register] - username exists: " + toAddUser.getUsername());
                        text = "Username exists";
                        context.addMessage("form:username", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
                    }
                } catch (UserDaoException ex) {
                    log.error("[AdminBean.register] - error while retrieving values from DB, message is:  " + ex.getMessage());
                    context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "DB error"));
                    return null;
                }
            }
            
            if (toAddUser.getEmail().equals("")) {
                log.error("[AdminBean.register] - email is empty");
                text = "Email is empty";
                context.addMessage("form:email", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!toAddUser.getEmail().matches("[\\w\\.-]*[a-zA-Z0-9_]@[\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]")) {
                log.error("[AdminBean.register] - email is not in right format: " + toAddUser.getEmail());
                text = "Email is not in correct format";
                context.addMessage("form:email", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(toAddUser.getEmail(), 70)) {
                log.error("[AdminBean.register] - email is not in allowed length: " + toAddUser.getEmail());
                text = "Email can't be  longer than 70";
                context.addMessage("form:email", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else {
                try {
                    log.info("[AdminBean.register] - user dao created");
                    ArrayList<User> emailList = (ArrayList<User>) DaoFactory.createUserDao().findWhereEmailEquals(toAddUser.getEmail());

                    if (emailList != null && emailList.size() > 0) {
                        log.error("[AdminBean.register] - email exists: " + toAddUser.getEmail());
                        text = "Email exists";
                        context.addMessage("form:email", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
                    }
                } catch (UserDaoException ex) {
                    log.error("[AdminBean.register] - error while retrieving values from DB, message is:  " + ex.getMessage());
                    context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "DB error"));
                    return null;
                }
            }
            
            if (toAddUser.getPassword().equals("")) {
                log.error("[AdminBean.register] - password is empty");
                text = "Password is empty";
                context.addMessage("form:password", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAlphaNumerical(toAddUser.getPassword())) {
                log.error("[AdminBean.register] - user's password is not in allowed format: " + toAddUser.getPassword());
                text = "Password must be alphanumerical";
                context.addMessage("form:password", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(toAddUser.getPassword(), 40)) {
                log.error("[AdminBean.register] - password is not in allowed length: " + toAddUser.getPassword());
                text = "Password can't be  longer than 40";
                context.addMessage("form:password", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (!toAddUser.getPassword().equals(password2)) {
                log.error("[AdminBean.register] - passwords do not match: " + toAddUser.getPassword() + ", " + password2);
                text = "Passwords do not match";
                context.addMessage("form:password2", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (context.getMessageList().size() > 0) {
                log.error("[AdminBean.register] - there are errors with the form");
                return null;
            } else {
                log.info("[AdminBean.register] - adding user: " + toAddUser.getUsername());

                User currentUser = new User();
                currentUser.setUsername(toAddUser.getUsername());
                currentUser.setName(toAddUser.getName());
                currentUser.setEmail(toAddUser.getEmail());
                currentUser.setUserTypeId(1);
                currentUser.setRegisterDate(new Date());                
                try {
                    currentUser.setPassword(CommonUtils.convertMd5(toAddUser.getPassword()));
                } catch (NoSuchAlgorithmException ex) {
                    log.error("[AdminBean.register] - error while converting string to md5, message is:" + ex.getMessage());
                    context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "General error with MD5"));
                    return null;
                }
                
                // Insert user
                DaoFactory.createUserDao().insert(currentUser);
                log.info("[AdminBean.addUser] - user inserted to db: " + toAddUser.getUsername());

                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Successfully added"));
                context.getExternalContext().getFlash().setKeepMessages(true);
                return "manageUsers.xhtml?faces-redirect=true";

            }
            
        } catch (Exception ex) {
            log.error("[AdminBean.register] - General exception, message is:  " + ex.getMessage());
            context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "General error"));
            return null;
        }
    }
    
    /**
     * Add source
     * 
     * @return 
     */
    public String addSource() {
        log.debug("[AdminBean.addSource] started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        
        try {
            
            if (toAddSource.getName() != null && !toAddSource.getName().equals("")) {
                toAddSource.setName(toAddSource.getName().trim());
            } else {
                toAddSource.setName("");
            }
            
            if (toAddSource.getName().equals("")) {
                log.error("[AdminBean.addSource] - name is empty");
                text = "Address is empty";
                context.addMessage("form:address", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(toAddSource.getName(), 240)) {
                log.error("[AdminBean.addSource] - user's name is not in allowed length: " + toAddSource.getName());
                text = "Address can't be longer than 240 characters";
                context.addMessage("form:address", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else {
                try {
                    log.debug("[AdminBean.addSource] - source dao created");
                    ArrayList<Source> sourceList = (ArrayList<Source>) DaoFactory.createSourceDao().findWhereNameEquals(toAddSource.getName());

                    if (sourceList != null && sourceList.size() > 0) {
                        log.error("[AdminBean.addSource] - username exists: " + toAddSource.getName());
                        text = "Address exists";
                        context.addMessage("form:address", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
                    }
                } catch (SourceDaoException ex) {
                    log.error("[AdminBean.addSource] - error while retrieving values from DB, message is:  " + ex.getMessage());
                    context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "DB error"));
                    return null;
                }
            }
            
            if (context.getMessageList().size() > 0) {
                log.error("[AdminBean.addSource] - there are errors with the form");
                return null;
            } else {
                log.info("[AdminBean.addSource] - adding user: " + toAddSource.getName());

                Source source = new Source();
                
                source.setName(toAddSource.getName());
                
                // Insert user
                DaoFactory.createSourceDao().insert(source);
                log.info("[AdminBean.addSource] - source inserted to db: " + toAddSource.getName());

                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Successfully added"));
                context.getExternalContext().getFlash().setKeepMessages(true);
                return "manageSources.xhtml?faces-redirect=true";

            }
            
        } catch (Exception ex) {
            log.error("[AdminBean.addSource] - General exception, message is:  " + ex.getMessage());
            context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "General error"));
            return null;
        }
        
    }
    
    /**
     * Add course
     * 
     * @return 
     */
    public String addCourse() {
        log.debug("[AdminBean.addCourse] started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        
        try {
            
            if (toAddWebResource.getTitle() != null && !toAddWebResource.getTitle().equals("")) {
                toAddWebResource.setTitle(toAddWebResource.getTitle().trim());
            } else {
                toAddWebResource.setTitle("");
            }
            
            if (toAddWebResource.getDescription() != null && !toAddWebResource.getDescription().equals("")) {
                toAddWebResource.setDescription(toAddWebResource.getDescription().trim());
            } else {
                toAddWebResource.setDescription("");
            }
            
            if (toAddWebResource.getUrl() != null && !toAddWebResource.getUrl().equals("")) {
                toAddWebResource.setUrl(toAddWebResource.getUrl().trim());
            } else {
                toAddWebResource.setUrl("");
            }
            
            if (toAddWebResource.getTitle().equals("")) {
                log.error("[AdminBean.addCourse] - name is empty");
                text = "Title is empty";
                context.addMessage("form:title", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(toAddWebResource.getTitle(), 240)) {
                log.error("[AdminBean.addCourse] - user's name is not in allowed length: " + toAddWebResource.getTitle());
                text = "Title can't be longer than 240 characters";
                context.addMessage("form:title", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (toAddWebResource.getDescription().equals("")) {
                log.error("[AdminBean.addCourse] - Description is empty");
                text = "Description is empty";
                context.addMessage("form:description", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (toAddWebResource.getUrl().equals("")) {
                log.error("[AdminBean.addCourse] - url is empty");
                text = "URL is empty";
                context.addMessage("form:url", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(toAddWebResource.getUrl(), 240)) {
                log.error("[AdminBean.addCourse] - url  is to long " + toAddWebResource.getUrl());
                text = "URL can't be  longer than 240";
                context.addMessage("form:url", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else {
                try {
                    log.info("[AdminBean.addCourse] - user dao created");
                    ArrayList<WebResource> webResourceList = (ArrayList<WebResource>) DaoFactory.createWebResourceDao().findWhereUrlEquals(toAddWebResource.getUrl());

                    if (webResourceList != null && webResourceList.size() > 0) {
                        log.error("[AdminBean.addCourse] - url exists: " + toAddWebResource.getUrl());
                        text = "URL exists";
                        context.addMessage("form:url", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
                    }
                } catch (WebResourceDaoException ex) {
                    log.error("[AdminBean.addCourse] - error while retrieving values from DB, message is:  " + ex.getMessage());
                    context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "DB error"));
                    return null;
                }
            }
            
            if (context.getMessageList().size() > 0) {
                log.error("[AdminBean.addCourse] - there are errors with the form");
                return null;
            } else {
                log.info("[AdminBean.addCourse] - adding course: " + toAddWebResource.getTitle());

                WebResource webResource =  new WebResource();
                webResource.setTitle(toAddWebResource.getTitle());
                webResource.setDescription(toAddWebResource.getDescription());
                webResource.setInsertDate(new Date());
                webResource.setWebResourceTypeId(WebResourceTypeEnum.COURSE.getId());
                
                // Insert user
                DaoFactory.createWebResourceDao().insert(webResource);
                log.info("[AdminBean.addCourse] - webresource inserted to db: " + toAddWebResource.getTitle());

                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Successfully added"));
                context.getExternalContext().getFlash().setKeepMessages(true);
                LoginBean loginBean = (LoginBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("loginBean");
                if (loginBean.isIsAdmin()) {
                    return "manageCourses.xhtml?faces-redirect=true";
                } else {
                    return "userManageCourses.xhtml?faces-redirect=true";
                }

            }
            
        } catch (Exception ex) {
            log.error("[AdminBean.addCourse] - General exception, message is:  " + ex.getMessage());
            context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "General error"));
            return null;
        }
        
    }
    
    /**
     * Add instructor
     * 
     * @return 
     */
    public String addInstructor() {
        log.debug("[AdminBean.addInstructor] started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        
        try {
            
            if (toAddWebResource.getTitle() != null && !toAddWebResource.getTitle().equals("")) {
                toAddWebResource.setTitle(toAddWebResource.getTitle().trim());
            } else {
                toAddWebResource.setTitle("");
            }
            
            if (toAddWebResource.getDescription() != null && !toAddWebResource.getDescription().equals("")) {
                toAddWebResource.setDescription(toAddWebResource.getDescription().trim());
            } else {
                toAddWebResource.setDescription("");
            }
            
            if (toAddWebResource.getUrl() != null && !toAddWebResource.getUrl().equals("")) {
                toAddWebResource.setUrl(toAddWebResource.getUrl().trim());
            } else {
                toAddWebResource.setUrl("");
            }
            
            if (toAddWebResource.getTitle().equals("")) {
                log.error("[AdminBean.addCourse] - name is empty");
                text = "Title is empty";
                context.addMessage("form:title", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(toAddWebResource.getTitle(), 240)) {
                log.error("[AdminBean.addCourse] - user's name is not in allowed length: " + toAddWebResource.getTitle());
                text = "Title can't be longer than 240 characters";
                context.addMessage("form:title", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (toAddWebResource.getDescription().equals("")) {
                log.error("[AdminBean.addCourse] - Description is empty");
                text = "Description is empty";
                context.addMessage("form:description", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (toAddWebResource.getUrl().equals("")) {
                log.error("[AdminBean.addCourse] - url is empty");
                text = "URL is empty";
                context.addMessage("form:url", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(toAddWebResource.getUrl(), 240)) {
                log.error("[AdminBean.addCourse] - url  is to long " + toAddWebResource.getUrl());
                text = "URL can't be  longer than 240";
                context.addMessage("form:url", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else {
                try {
                    log.info("[AdminBean.addCourse] - user dao created");
                    ArrayList<WebResource> webResourceList = (ArrayList<WebResource>) DaoFactory.createWebResourceDao().findWhereUrlEquals(toAddWebResource.getUrl());

                    if (webResourceList != null && webResourceList.size() > 0) {
                        log.error("[AdminBean.addCourse] - url exists: " + toAddWebResource.getUrl());
                        text = "URL exists";
                        context.addMessage("form:url", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
                    }
                } catch (WebResourceDaoException ex) {
                    log.error("[AdminBean.addCourse] - error while retrieving values from DB, message is:  " + ex.getMessage());
                    context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "DB error"));
                    return null;
                }
            }
            
            if (context.getMessageList().size() > 0) {
                log.error("[AdminBean.addCourse] - there are errors with the form");
                return null;
            } else {
                log.info("[AdminBean.addCourse] - adding course: " + toAddWebResource.getTitle());

                WebResource webResource =  new WebResource();
                webResource.setTitle(toAddWebResource.getTitle());
                webResource.setDescription(toAddWebResource.getDescription());
                webResource.setInsertDate(new Date());
                webResource.setWebResourceTypeId(WebResourceTypeEnum.INSTRUCTOR.getId());
                
                // Insert user
                DaoFactory.createWebResourceDao().insert(webResource);
                log.info("[AdminBean.addCourse] - webresource inserted to db: " + toAddWebResource.getTitle());

                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Successfully added"));
                context.getExternalContext().getFlash().setKeepMessages(true);
                return "manageInstructors.xhtml?faces-redirect=true";

            }
            
        } catch (Exception ex) {
            log.error("[AdminBean.addCourse] - General exception, message is:  " + ex.getMessage());
            context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "General error"));
            return null;
        }
        
    }
    
    /**
     * Add institution
     * 
     * @return 
     */
    public String addInstitution() {
        log.debug("[AdminBean.addInstitution] started");
        FacesContext context = FacesContext.getCurrentInstance();
        String text;
        String errorText = "ERROR";
        
        try {
            
            if (toAddWebResource.getTitle() != null && !toAddWebResource.getTitle().equals("")) {
                toAddWebResource.setTitle(toAddWebResource.getTitle().trim());
            } else {
                toAddWebResource.setTitle("");
            }
            
            if (toAddWebResource.getDescription() != null && !toAddWebResource.getDescription().equals("")) {
                toAddWebResource.setDescription(toAddWebResource.getDescription().trim());
            } else {
                toAddWebResource.setDescription("");
            }
            
            if (toAddWebResource.getUrl() != null && !toAddWebResource.getUrl().equals("")) {
                toAddWebResource.setUrl(toAddWebResource.getUrl().trim());
            } else {
                toAddWebResource.setUrl("");
            }
            
            if (toAddWebResource.getTitle().equals("")) {
                log.error("[AdminBean.addCourse] - name is empty");
                text = "Title is empty";
                context.addMessage("form:title", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(toAddWebResource.getTitle(), 240)) {
                log.error("[AdminBean.addCourse] - user's name is not in allowed length: " + toAddWebResource.getTitle());
                text = "Title can't be longer than 240 characters";
                context.addMessage("form:title", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (toAddWebResource.getDescription().equals("")) {
                log.error("[AdminBean.addCourse] - Description is empty");
                text = "Description is empty";
                context.addMessage("form:description", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            }
            
            if (toAddWebResource.getUrl().equals("")) {
                log.error("[AdminBean.addCourse] - url is empty");
                text = "URL is empty";
                context.addMessage("form:url", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else if (!CommonUtils.isAllowedLength(toAddWebResource.getUrl(), 240)) {
                log.error("[AdminBean.addCourse] - url  is to long " + toAddWebResource.getUrl());
                text = "URL can't be  longer than 240";
                context.addMessage("form:url", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
            } else {
                try {
                    log.info("[AdminBean.addCourse] - user dao created");
                    ArrayList<WebResource> webResourceList = (ArrayList<WebResource>) DaoFactory.createWebResourceDao().findWhereUrlEquals(toAddWebResource.getUrl());

                    if (webResourceList != null && webResourceList.size() > 0) {
                        log.error("[AdminBean.addCourse] - url exists: " + toAddWebResource.getUrl());
                        text = "URL exists";
                        context.addMessage("form:url", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", text));
                    }
                } catch (WebResourceDaoException ex) {
                    log.error("[AdminBean.addCourse] - error while retrieving values from DB, message is:  " + ex.getMessage());
                    context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "DB error"));
                    return null;
                }
            }
            
            if (context.getMessageList().size() > 0) {
                log.error("[AdminBean.addCourse] - there are errors with the form");
                return null;
            } else {
                log.info("[AdminBean.addCourse] - adding course: " + toAddWebResource.getTitle());

                WebResource webResource =  new WebResource();
                webResource.setTitle(toAddWebResource.getTitle());
                webResource.setDescription(toAddWebResource.getDescription());
                webResource.setInsertDate(new Date());
                webResource.setWebResourceTypeId(WebResourceTypeEnum.INSTITUTION.getId());
                
                // Insert user
                DaoFactory.createWebResourceDao().insert(webResource);
                log.info("[AdminBean.addCourse] - webresource inserted to db: " + toAddWebResource.getTitle());

                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Successfully added"));
                context.getExternalContext().getFlash().setKeepMessages(true);
                return "manageInstitutions.xhtml?faces-redirect=true";

            }
            
        } catch (Exception ex) {
            log.error("[AdminBean.addCourse] - General exception, message is:  " + ex.getMessage());
            context.addMessage("form", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "General error"));
            return null;
        }
        
    }
    
    /*----Getter Setters---- */

    public User getToBeRemovedUser() {
        return toBeRemovedUser;
    }

    public void setToBeRemovedUser(User toBeRemovedUser) {
        this.toBeRemovedUser = toBeRemovedUser;
    }

    public ArrayList<User> getLastUsers() {
        return lastUsers;
    }

    public ArrayList<User> getAllUsers() {
        return allUsers;
    }

    public WebResource getToBeRemovedWebResource() {
        return toBeRemovedWebResource;
    }

    public void setToBeRemovedWebResource(WebResource toBeRemovedWebResource) {
        this.toBeRemovedWebResource = toBeRemovedWebResource;
    }

    public ArrayList<WebResource> getAllCourses() {
        return allCourses;
    }

    public ArrayList<WebResource> getAllInstructors() {
        return allInstructors;
    }

    public ArrayList<WebResource> getAllInstitutions() {
        return allInstitutions;
    }

    public ArrayList<Source> getAllSources() {
        return allSources;
    }

    public Source getToBeRemovedSource() {
        return toBeRemovedSource;
    }

    public void setToBeRemovedSource(Source toBeRemovedSource) {
        this.toBeRemovedSource = toBeRemovedSource;
    }

    public User getToAddUser() {
        if (toAddUser == null) {
            toAddUser = new User();
        }
        return toAddUser;
    }

    public void setToAddUser(User toAddUser) {
        this.toAddUser = toAddUser;
    }

    public WebResource getToAddWebResource() {
        if (toAddWebResource == null) {
            toAddWebResource = new WebResource();
        }
        return toAddWebResource;
    }

    public void setToAddWebResource(WebResource toAddWebResource) {
        this.toAddWebResource = toAddWebResource;
    }

    public Source getToAddSource() {
        if (toAddSource == null) {
            toAddSource = new Source();
        }
        return toAddSource;
    }

    public void setToAddSource(Source toAddSource) {
        this.toAddSource = toAddSource;
    }

    public String getPassword2() {
        return password2;
    }

    public void setPassword2(String password2) {
        this.password2 = password2;
    }
    
    

}
